//商品id
var id;
//当前筛选分类id
var curCateId;
//当前筛选分组id
var curGroupId;
//已有推荐商品列表实例
var $table = $("#exist-rec-goods");
//可选推荐商品列表实例
var $tableAdd = $("#add-rec-goods");

/**
 * 获得的商品参数
 */
var goodsId = "";
var goodsName = "";
var classifyId = "";
var indexGroupId = "";
var goodsUrl = "";
var goodsType = 0;

var goodsTypeShow = "";

$(function () {
    id = getvl("id");
    goodsId = id;
    if (id != undefined && id != "") {
        loadData(id);
    }
});

//载入数据
function loadData(id) {
    $.ajax({
        type: "get",
        url: urlcore + "/api/goods/selectOne?id=" + id,
        dataType: "json",
        headers: {"Content-Type": "application/json;charset=UTF-8"},
        data: {},
        success: function (cbdata) {
            var goods = cbdata.data;
            if (cbdata.success == true) {
                goodsName = goods.goodsName;
                classifyId = goods.classifyId;
                indexGroupId = goods.indexGroupId;
                goodsUrl = goods.goodsUrl;
                goodsType = goods.goodsType;

                if (goodsType == 0)
                    goodsTypeShow = "蜜哆哆";
                else if (goodsType == 1)
                    goodsTypeShow = "蜜雅阁";
                else if (goodsType == 2)
                    goodsTypeShow = "品牌馆";
                $("#goodsName").val(goodsName);
                $("#goodsType").val(goodsTypeShow);
                $("#goodsUrl").attr("src", goodsUrl);

                //生成分组下拉框
                executeGetFirstSecGroup(goodsType);
                //初始化已有推荐和待选推荐表格
                initExistRecTable();
                initUnRecTable()
            } else {
                alert(data.msg);
            }
        },
        error: function () {
            alert("获取商品失败");
        }
    });


}


//初始化已有推荐列表
function initExistRecTable() {

    var url = urlcore + "/api/goodsRecommend/getAdminGoodsRecListByGoodsId";
    initTable($table, "post", url, 0);
}

//初始化待选推荐列表
function initUnRecTable() {
    var url = urlcore + "/api/goodsRecommend/getUnRecedGoodsListWithCategory";
    initTable($tableAdd, "post", url, 1);
}


var columns = [
    {
        checkbox: true,
    }, {
        title: "序号",
        align: "center",
        width: "50px",
        formatter: function (value, row, index) {
            return (index + 1);
        }
    }, {
        field: "id",
        title: "商品ID",
        halign: "center",
        align: "center",
        width: "80px"
    }, {
        field: "goodsName",
        title: "商品名称",
        halign: "center",
        sortable: true
    }, {
        field: "goodsUrl",
        title: "商品图片",
        align: "center",
        width: "150px",
        formatter: function (value, row, index) {
            return '<img style="width: 50px;height: auto" src="' + value + '" >';
        }
    }];

var queryParams = function (params, tag) {
    console.log("params:", params);
    console.log("tag:", tag);
    var param;
    if (tag == 0) {
        param = {
            goods: {
                id: goodsId
            },
            page: {
                offset: params.offset,
                current: params.offset / params.limit + 1,//bootstrap-table分页参数offset从0开始，计算的后端当前页参数current=(offset/limit+1)，
                size: params.limit
            },
            searchText:params.search
        };
    }

    //待选推荐
    if (tag == 1) {
        param = {
            goods: {
                id: goodsId,
                // "classifyId":classifyId,
                indexGroupId:curGroupId,
                goodsType: goodsType
            },
            page: {
                offset: params.offset,
                current: params.offset / params.limit + 1,//bootstrap-table分页参数offset从0开始，计算的后端当前页参数current=(offset/limit+1)，
                size: params.limit
            },
            searchText:params.search
        };
    }
    return param;
}

//初始化表格，有已有推荐和待选的商品两类表格 tableins:表格实例 ,
// insTag 0表示当前已有推荐表格 1表示待添加推荐的表格
function initTable(tableins, method, url, insTag) {
    tableins.bootstrapTable({
        columns: columns,
        method: method,
        url: url,
        dataType: "json",
        queryParams: function (params) {
            return queryParams(params, insTag);
        },
        //返回数据预处理
        responseHandler: function (cbdata) {
            console.log(cbdata);
            if (null != cbdata.data && null != cbdata.data.records) {
                var records = cbdata.data.records;
                var res = {
                    //如果采用server端分页，必须有rows和total这两部分数据
                    "rows": records,
                    "total": cbdata.data.total
                };
                return res;
            } else return {"rows": [], "total": 0};
        },
        cache: false,
        // toolbar: '#toolbar',//自定义工具栏，不同表格工具栏不同，一个jQuery 选择器，指明自定义的toolbar 例如:#toolbar, .toolbar.
        pagination: true,//启用分页条
        sidePagination: "server",//分页方式client或server
        // pageNumber: 1,
        pageSize: 16,//每页大小
        pageList: [16, 32, 48, 64],//可以选择每页大小
        showRefresh: true,//显示刷新
        sortable: true,//是否启用排序
        clickToSelect: true,//设置true 将在点击行时，自动选择rediobox 和 checkbox
        search: true,//只是客户端搜索
        // searchText:"",//初始搜索文本
    });
}


// 点击移除按钮移出已推荐表
function rmFromRec() {
    indexGroupId = $("#curGroup").val();
    //get selections arr
    var selection = $table.bootstrapTable('getSelections');
    if (selection.length == 0) {
        alert("请先选择商品");
        return;
    }
    console.log(selection);
    confirm("确认从推荐列表中移除吗，不会影响到商品状态", function (callback) {
        if (callback) {
            rmRec();
        }
    });

    function rmRec() {
        var paramArr = [];
        for (var item of selection) {
            paramArr.push({
                goodsId: goodsId,
                recGoodsId: item.id,
            })
        }
        $.ajax({
            type: "POST",
            url: urlcore + "/api/goodsRecommend/deleteRecGoodsBatch",
            dataType: "json",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(paramArr),
            success: function (data) {
                $table.bootstrapTable('refresh');
                $tableAdd.bootstrapTable('refresh');
                console.log("rmbatchrecgoodsdata", data);
                alert("批量移除推荐商品成功！");
            },
            error: function () {
                alert("失败");
            }
        });
    }
}

//点击按钮添加到商品推荐，更新已推荐表
function addToRec() {
    var selection = $tableAdd.bootstrapTable('getSelections');
    if (goodsId == undefined || goodsId == "") {
        console.log("获取商品goodsId错误");
        alert("获取商品goodsId错误");
        return;
    }
    if (selection.length == 0) {
        alert("请先选择商品");
        return;
    }
    //当前分组id
    indexGroupId = $("#curGroup").val();
    //get selections arr
    console.log(selection);
    var paramArr = [];
    for (var item of selection) {
        paramArr.push({
            goodsId: goodsId,
            recGoodsId: item.id,
        })
    }
    $.ajax({
        type: "POST",
        url: urlcore + "/api/goodsRecommend/addRecGoodsBatch",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(paramArr),
        success: function (data) {
            $tableAdd.bootstrapTable('refresh');
            $table.bootstrapTable('refresh');
            console.log("batchrecgoodsdata", data);
            alert("批量添加推荐商品成功！");
        },
        error: function () {
            alert("添加失败");
        }
    });
    //refresh table
}


//分组改变，在管理分组商品时刷新列表
$("#curGroup").change(function () {
    curGroupId = $("#curGroup").val();
    $tableAdd.bootstrapTable("refresh");
});

//获取一二级分组（分开）
function executeGetFirstSecGroup(selectedGroupType) {
    $.ajax({
        url: urlcore + "/api/indexGroup/getAllGroup",
        method: "get",
        dataType: "json",
        // async: false,//禁止异步
        contentType: "application/json;charset=UTF-8",
        data: {
            groupType: selectedGroupType,
        },
        success: function (cbdata) {
            console.log(cbdata.data);
            firstGroupArr = cbdata.data.firstGroupList;
            secondGroupArr = cbdata.data.secondGroupList;
            //生成选择分组的optgroup
            generateOptgroupHtml(firstGroupArr, secondGroupArr);
        },
        error: function (data) {
            alert("获取分组失败");
        }
    });
}

//生成选择分组的optgroup
function generateOptgroupHtml(firstGroupArr, secondGroupArr) {

    var optgroupHtmlStr = "";
    //生成optgroup
    for (var item of firstGroupArr) {
        var htmlStr = getGroupOptionHtml(item, 0);
        optgroupHtmlStr += htmlStr;
    }
    $("#curGroup").append(optgroupHtmlStr);

    //生成optgroup的option
    for (var item of secondGroupArr) {
        var htmlStr = getGroupOptionHtml(item, 1);
        var parentId = item.pid;
        $("#curGroup").find('optgroup[data-id="' + parentId + '"]').append(htmlStr);
    }
}

//生成分组选择框的optgroup（tag为0）或option（tag为1）
function getGroupOptionHtml(item, tag) {
    var htmlStr = "";
    if (tag == 0) {
        htmlStr = "   <optgroup data-id=\"" + item.id + "\" label=\"" + item.title + "\">\n" +
            "    </optgroup>";
    }
    if (tag == 1) {
        htmlStr = "<option value=\"" + item.id + "\">" + item.title + "</option>";
    }
    return htmlStr;
}
